import requests
import json
import re

def convert_alias_to_path(alias):
    """将菜单alias转换为路由路径"""
    parts = alias.split('.')[1:]  # 移除system.前缀
    converted_parts = []
    for part in parts:
        # 处理下划线格式：resource_Engineering -> resource-engineering
        if '_' in part:
            sub_parts = part.split('_')
            part = sub_parts[0] + ''.join([p.capitalize() for p in sub_parts[1:]])
        # 驼峰转短横线：AbcDef -> abc-def
        part = re.sub(r'(?<!^)(?=[A-Z])', '-', part).lower()
        converted_parts.append(part)
    return '/'.join(converted_parts)

def generate_ruoyi_routes(menu, parent_path=''):
    """递归生成若依路由配置"""
    routes = []

    # 过滤非启用菜单（兼容字符串和数字类型）
    if str(menu.get('enableMenu', 0)) != '1':
        return routes

    # 生成当前路径
    current_path = convert_alias_to_path(menu['alias'])
    full_path = f"{parent_path}/{current_path}" if parent_path else current_path

    # 生成组件路径（仅叶子节点需要）
    component = None
    if menu.get('templateUrl'):
        # 转换路径：bms/views/.../file.html -> @/views/.../file.vue
        vue_path = menu['templateUrl'] \
            .replace('bms/views/', '') \
            .replace('.html', '.vue')
        component = f"@/views/{vue_path}"

    # 处理子菜单
    children = []
    for child in menu.get('children', []):
        child_routes = generate_ruoyi_routes(child, full_path)
        children.extend(child_routes)

    # 构建路由对象
    route = {
        "path": current_path,
        "component": "Layout",
        "meta": {
            "title": menu['name'],
            "icon": menu.get('menuIcon') or 'el-icon-menu'
        }
    }

    # 叶子节点处理
    if component and not children:
        route['children'] = [{
            "path": "",
            "component": component,
            "name": menu['name'].replace(' ', ''),
            "meta": route['meta']
        }]
    elif children:
        route['children'] = children

    routes.append(route)
    return routes

def main():
    # 请求菜单数据
    url = "http://uatbms.einyun.com/portal/sys/sysMenu/v1/getCurrentUserMenu"
    headers = {
        "Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJKWkZXWV9hZG1pbi5iNzBhYmQyZC1hZTQ5LTRmNTAtODdiNC0yN2RkN2MwMzBhMjYiLCJ0ZW5hbnRJZCI6ImI3MGFiZDJkLWFlNDktNGY1MC04N2I0LTI3ZGQ3YzAzMGEyNiIsImV4cCI6MTc0ODQxMjY1MSwiaWF0IjoxNzQ4MzI2MjUxfQ.F1LFqNdVyYRYhOKIAMvrmi15zlWYTbxvRpYe0i6rlbwyTgUW7j-FDwMKrv8MrSOboBSyTnksQIbXXdmXFmLqyQ",
        "tenant-id": "b70abd2d-ae49-4f50-87b4-27dd7c030a26"
    }
    params = {"menuAlias": "system.front_menu"}

    response = requests.get(url, headers=headers, params=params)
    data = response.json()

    # 生成路由配置
    final_routes = []
    for top_menu in data.get('children', []):
        final_routes.extend(generate_ruoyi_routes(top_menu))

    # 打印结果
    print(json.dumps(final_routes, indent=2, ensure_ascii=False))

if __name__ == "__main__":
    main()
